package com.banyuan.servlet.opus;

import com.alibaba.fastjson.JSON;
import com.banyuan.dao.OpusDao;
import com.banyuan.domain.Opus;
import com.banyuan.domain.ResData;
import com.banyuan.utils.AuthorUtils;
import com.banyuan.utils.CommonUtils;
import com.banyuan.utils.DBUtils;
import com.banyuan.utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/opus/update")
public class UpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String intro = req.getParameter("intro");
        String name = req.getParameter("name");
        String typeId = req.getParameter("typeId");
        String icon = req.getParameter("icon");

        // 先判断传进来的值

        if (CommonUtils.isEmpty(intro) || CommonUtils.isEmpty(name) || CommonUtils.isEmpty(typeId) ||
                CommonUtils.isEmpty(icon) ) {
            ResData resData = new ResData(10001,"输入项为空",null);
            resp.getWriter().write(JSON.toJSONString(resData));
            return;
        }

// 通过传进来的id去查询authorid，在和session里面的authorid是否一样，不一样的话就return
        ResultSet resultSet = null;
        Integer loginId = AuthorUtils.getLoginId(req);

        try {
            resultSet = OpusDao.selectOpusById(Integer.parseInt(id));
            Opus opus = DBUtils.resultToBeanOne(resultSet, Opus.class);
            if (!loginId.equals(opus.getAuthorId())) {
                ResData resData = new ResData(10002,"不能修改他人的书本",null);
                resp.getWriter().write(JSON.toJSONString(resData));
                return;
            }
            opus.setName(name);
            opus.setIntro(intro);
            opus.setIcon(icon);
            opus.setTypeId(Integer.valueOf(typeId));

            int update = OpusDao.update(opus);
            if (update > 0 ) {
                ResData resData = new ResData(200,"修改成功",null);
                resp.getWriter().write(JSON.toJSONString(resData));
            } else {
                ResData resData = new ResData(10003,"修改失败",null);
                resp.getWriter().write(JSON.toJSONString(resData));
            }


        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtils.closeBy(resultSet);
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
